package main

import (
	"fmt"
)

// 自己实现的链表
/****************************************/
/**
head := NewListNode([]int{1, 2, 3})
printLinkedList(head)
*/

type ListNode struct {
	Val  int
	Next *ListNode
}

func NewListNode(nums []int) *ListNode {
	return createLinkedList(nums)
}

func createLinkedList(nums []int) *ListNode {

	if len(nums) == 0 { return nil }

	head := &ListNode{ Val: nums[0] }

	cur := head
	for i := 1; i < len(nums); i++ {
		cur.Next = &ListNode{ Val: nums[i] }
		cur = cur.Next
	}

	return head
}

func printLinkedList(head *ListNode) {

	cur := head
	for cur != nil {
		fmt.Print(cur.Val, "->")
		cur = cur.Next
	}
	fmt.Println("NULL")
}
/****************************************/

/**
执行用时：16 ms, 在所有 Go 提交中击败了21.82%的用户
内存消耗：4.6 MB, 在所有 Go 提交中击败了90.58%的用户
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {

	dummy := &ListNode{Val: 0}
	cur := dummy

	t := 0
	for l1 != nil || l2 != nil || t != 0 {
		if l1 != nil {
			t += l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			t += l2.Val
			l2 = l2.Next
		}
		cur.Next = &ListNode{Val: t % 10}
		cur = cur.Next
		t /= 10
	}
	return dummy.Next
}

func main() {

	l1 := NewListNode([]int{2, 4, 3})
	l2 := NewListNode([]int{5, 6, 4})
	printLinkedList(addTwoNumbers(l1, l2))  // 7->0->8->NULL
}
